package com.example.springbootServiceNetwork.demos.web.Service.Impl;

import cn.hutool.core.io.FileUtil;
import com.example.springbootServiceNetwork.demos.web.Config.JwtInfo;
import com.example.springbootServiceNetwork.demos.web.Config.Result;
import com.example.springbootServiceNetwork.demos.web.Config.ResultEnum;
import com.example.springbootServiceNetwork.demos.web.Entity.FileInfo;
import com.example.springbootServiceNetwork.demos.web.Service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.example.springbootServiceNetwork.demos.web.Tool.WrapperMethodUtil.bollPurvieTool;


@Service
public class FileServiceImpl implements FileService {

    @Value("${file.filePath}")
    private String filePath;
    @Value("${file.uploadPath}")
    private String uploadPath;
    @Value("${file.readFilePath}")
    private String readFilePath;

    /**
     * 文件上传
     *  file
     */
    @Override
    public Result fileUpload(MultipartFile file){
        Result r = new Result();
        String Rrl= filePath;//服务器访问前缀
        String filePath =uploadPath; //服务器的存放路径
        if (file.isEmpty()){
            r.setCode(ResultEnum.BADREQUEST.getCode());
            r.setMsg("文件上传失败！");
        }else {
            //取出文件
            String OriginalFilename=file.getOriginalFilename();
           //文件重命名
            String fileName = null;
            if (OriginalFilename != null) {
                fileName = System.currentTimeMillis()+"."+OriginalFilename.substring(OriginalFilename.lastIndexOf(".")+1);
            }
            //拼接文件存放地址
            File dest=new File(filePath+fileName);
            //判断文件路径是否存在  如果不存在就创建文件路径
            if (dest.getParentFile().exists())
                dest.getParentFile().mkdirs();
            try {
                HashMap<String,String> map =new HashMap<>();

                //文件保存
                File isSaved =  FileUtil.writeBytes(file.getBytes(), filePath+fileName);
                map.put("filePath",Rrl+fileName);
                map.put("fileName",fileName);
                r.setData(map);
                //服务器地址路径 + 文件名字
                //r.setData( fileName);//本地
                r.setCode(ResultEnum.SUCCESS.getCode());
                r.setMsg("上传成功");

                //抛出异常
            } catch (IOException e) {
                e.fillInStackTrace();
                r.setData(e);
            }
        }
        return r;
    }

    /**
     * 文件删除
     *  fileName
     */
    @Override
    public Result fileDelete(String fileName){

        File file = new File(uploadPath+fileName);
        Result r = new Result();
        if(!file.exists()){
            r.setData("删除文件失败："+fileName+"不存在！");
            r.setCode(ResultEnum.SUCCESS.getCode());
            r.setMsg("删除失败");
        }else{
            //判断这是不是一个文件，ps：有可能是文件夹
            if(file.isFile()){
                file.delete();//删除
                r.setCode(ResultEnum.SUCCESS.getCode());
                r.setMsg("删除成功");
            }else {
                r.setCode(ResultEnum.DB_UPDATE_FAILURE.getCode());
                r.setMsg("不能删除文件夹！");
            }
        }

        return  r;
    }

    /**
     * 获取文件信息
     */
    @Override
    public Result queryFileInfo(JwtInfo jwtInfo){
        Result result = new Result();
         try{
          if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
              String folderPath = readFilePath;
              File folder = new File(folderPath);
              File[] files = folder.listFiles();
              if (files != null) {
                  List<FileInfo> fileInfos = new ArrayList<>();
                  for (File file : files) {
                      if (file.isFile()){
                          String[] fileList = file.getName().split("\\.");
                          FileInfo fileInfo = new FileInfo();
                          fileInfo.setFileTitle(fileList[0]);
                          fileInfo.setFileName(file.getName());
                          fileInfo.setFileType(fileList[1]);
                          fileInfo.setFileLength((int) file.length());
                          fileInfos.add(fileInfo);
                      }
                  }
                  result.setCode(ResultEnum.SUCCESS.getCode());
                  result.setMsg(ResultEnum.SUCCESS.getData());
                  result.setCount(fileInfos.size());
                  result.setData(fileInfos);
              }else {
                  result.setCode(ResultEnum.SUCCESS.getCode());
                  result.setMsg("文件数据为空");
              }
          }else {
              result.setCode(ResultEnum.SUCCESS.getCode());
              result.setMsg("您暂无权限！");
          }
         }catch (Exception e){
             result.setCode(ResultEnum.UNKNOWNERROR.getCode());
             result.setMsg(ResultEnum.DB_QUERY_FAILURE.getData());
             result.setData(e.getCause());
         }
         return  result;
    }
}
